package com.groot.medical.service;

import java.sql.*;
import java.util.List;

import com.groot.common.util.MedicalDBUtil;
import com.groot.medical.dao.UserDao;
import com.groot.medical.dao.UserDaoImpl;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.SysUser;
import com.groot.medical.entity.UserRole;

public class UserServiceImpl implements UserService {
	private UserDao userDao = new UserDaoImpl();

	@Override
	public SysUser findById(String userId, String password) {
		
		Connection conn = null;
		try {
			conn = MedicalDBUtil.getConnection();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		try{
			conn.setAutoCommit(false);
			SysUser sysUser = userDao.loginById(userId, password);
			conn.commit();
			return sysUser;
		}catch(Exception e){
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			throw new RuntimeException("出问题了-----");
		}
	}


	@Override
	public int addUser(String[] roleIds,SysUser sysUser) {
		for(int i=0;i<roleIds.length;i++){
			UserRole userRole = new UserRole();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleIds[i]);
			userDao.addUserAndMenu(userRole);
		}
		return userDao.addUser(sysUser);
	}

	@Override
	public SysUser findUserById(String userid) {
		SysUser sysUser = userDao.findUserById(userid);
		
		return sysUser;
	}

	@Override
	public int editUser(String[] roleIdList,SysUser sysUser) {
		for(int i=0;i<roleIdList.length;i++){
			UserRole userRole = new UserRole();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleIdList[i]);
			userDao.addUserAndMenu(userRole);
		}
		return userDao.editUser(sysUser);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PageBean<SysUser> findByPage(int pageNum, int pageSize) {
		//获取记录总条数
		int totalRecord = userDao.getALLUserCount();
		
		PageBean pegeBean = new PageBean<>(pageNum, pageSize, totalRecord);
		int startIndex = pegeBean.getStartIndex();
		pegeBean.setList(userDao.findUserByPage(startIndex,pageSize));
		return pegeBean;
	}


	@Override
	public List findAllUserList() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void delUserRole(String userid) {
		userDao.delUserRole(userid);
		
	}


	@Override
	public int deleteUserByUserId(String userid) {
		int i = 0;
		i = userDao.deleteUserByUserId(userid);
		if(i>0){
			userDao.delUserRole(userid);
		}
		return i;
	}


}
